﻿// ==PREPROCESSOR==
// @import "%fb2k_path%scripts\marc2003\v2\common.js"
// ==/PREPROCESSOR==

var username_file = settings_path + "username";
var username = read(username_file);
var api_key_file = settings_path + "api_key";
var api_key = read(api_key_file);
var artist = '';
var g_text = '';
var lfm_img = gdi.Image(images_path + "lastfm_red_small.gif");
on_item_focus_change();

function on_notify_data(name, data) {
	if(name == "lastfm_update" && data == 1) {
		username = read(username_file);
		api_key = read(api_key_file);
		artist = '';
		on_metadb_changed();
	}
}

function get_bio() {
	if(username.length == 0 || api_key.length != 32) return(fb.trace("WSH Biography: Can't contact Last.fm. Check your username / API KEY settings."));
	lastfm("&method=artist.getinfo&artist=" + encodeURIComponent(artist), "foo_wsh_lastfm_bio", function() {save_file();});
}

function save_file() {
	xmlDoc = xmlhttp.responsetext;
	try {
		ts = fso.OpenTextFile(filename, 2, true, -1);
		ts.WriteLine(xmlDoc);
		ts.close();
	} catch(e) {
	}
	artist = '';
	on_metadb_changed();
}

function on_size() {
	ww = window.Width;
	wh = window.Height;
	calc();
}

function on_paint(gr) {
	gr.FillSolidRect(0, 0, ww, wh, g_backcolor);
	if(username.length == 0 || api_key.length != 32) {
		gr.GdiDrawText("Last.fm username and/or API KEY is not set.", g_font, g_textcolor, 0, 0, ww, wh,DT_CENTER | DT_VCENTER | DT_CALCRECT | DT_NOPREFIX);
	} else if(g_metadb) {
		gr.GdiDrawText(g_text, g_font, g_textcolor, 6, offset + 56, ww-16, wh-offset,DT_WORDBREAK | DT_CALCRECT | DT_NOPREFIX);
		gr.FillSolidRect(0, 0, ww, 58, g_backcolor);
		gr.GdiDrawText(artist, gdi.Font("Verdana", 14, 1), g_textcolor_hl, 6, 5, ww-77, 24,DT_END_ELLIPSIS | DT_CALCRECT | DT_NOPREFIX);
		gr.GdiDrawText(addCommas(listeners) + " listeners,  " + addCommas(userplaycount) + " plays in your library.", gdi.Font("Verdana", 10, 0), g_textcolor_hl, 6, 31, ww-16, 24,DT_END_ELLIPSIS | DT_CALCRECT | DT_NOPREFIX);
		gr.DrawImage(lfm_img, ww-60, 8, 50, 18, 0, 0, 50, 18);
		gr.DrawLine(5, 29, ww-10, 29, 1, g_textcolor_hl);
	} else {
		gr.GdiDrawText("[no selection]", g_font, g_textcolor, 0, 0, ww, wh,DT_CENTER | DT_VCENTER | DT_CALCRECT | DT_NOPREFIX);
	}
}

function on_playback_new_track() {
	on_item_focus_change();
}

function on_metadb_changed() {
	if(!g_metadb || artist == fb.TitleFormat("%artist%").EvalWithMetadb(g_metadb)) {window.Repaint(); return; }
	g_text = '';
	listeners = userplaycount = 0;
	artist = fb.TitleFormat("%artist%").EvalWithMetadb(g_metadb);
	artist_folder = data_folder + fb.TitleFormat("$crc32(%artist%)").EvalWithMetadb(g_metadb);
	if(!fso.FolderExists(artist_folder)) fso.CreateFolder(artist_folder);
	filename = artist_folder + "\\artistinfo.xml";
	if(fso.fileExists(filename)) {
		file = fso.Getfile(filename);
		if(Date.parse(Date()) - Date.parse(file.DateLastModified) < 86400000) {
			try {
				ts = fso.OpenTextFile(filename,1, false, -1);
				g_text = ts.ReadAll();
				ts.close();
			} catch(e) {
			}
			 if(g_text.length > 0) {
				var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(g_text);
				try {
					g_text = xmlDoc.getElementsByTagName("content")[0].childNodes[0].nodeValue;
					g_text = decodeXML(g_text);
				} catch(e) {
					g_text = "This artist does not have a biography page on Last.fm.";
				}
				try { listeners = xmlDoc.getElementsByTagName("listeners")[0].childNodes[0].nodeValue; } catch(e) {listeners = 0;}
				try { userplaycount = xmlDoc.getElementsByTagName("userplaycount")[0].childNodes[0].nodeValue; } catch(e) {userplaycount = "no";}
				calc();
				window.Repaint();
			}
		} else {
			get_bio();
		}
	} else {
		get_bio();
	}
}

function calc() {
	temp_bmp = gdi.CreateImage(1, 1);
	temp_gr = temp_bmp.GetGraphics();
	arr = temp_gr.GdiDrawText(g_text, g_font, g_textcolor, 0, 0, ww, wh-40,DT_CENTER| DT_WORDBREAK | DT_VCENTER | DT_CALCRECT | DT_NOPREFIX).toArray();
	textheight = arr[3] - arr[1] + (wh)  + (g_text.count("\n") * 3);
	temp_bmp.ReleaseGraphics(temp_gr);
	temp_bmp.Dispose();
	temp_gr = null;
	temp_bmp = null;
	offset = 0;
}

function on_mouse_rbtn_up(x, y) {
	var _menu = window.CreatePopupMenu();
	var idx;
	_menu.AppendMenuItem(username.length > 0 && api_key.length == 32 && g_metadb ? MF_STRING : MF_GRAYED, 1, "Update");
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	_menu.AppendMenuItem(MF_STRING, 2, "Set your Last.fm username");
	_menu.AppendMenuItem(MF_STRING, 3, "Set your API KEY");
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	//_menu.AppendMenuItem(MF_STRING, 9, "Properties");
	_menu.AppendMenuItem(MF_STRING, 10, "Configure...");
	idx = _menu.TrackPopupMenu(x, y);
	switch(idx) {
		case 1:
			get_bio();
			break;
		case 2: 
			username = text_input_box("WSH Biography", "Please enter your Last.fm username", username_file);
			artist = null;
			on_metadb_changed();
			window.NotifyOthers("lastfm_update", 1);
			break;
		case 3:
			api_key = text_input_box("WSH Biography", "Please enter your Last.fm API KEY\n\nhttp://www.last.fm/api/account", api_key_file);
			artist = null;
			on_metadb_changed();
			window.NotifyOthers("lastfm_update", 1);
			break;
		case 9:
			window.ShowProperties();
			break;
		case 10:
			window.ShowConfigure();
			break;
	}
	_menu.Dispose();
	return true;
}

function on_mouse_wheel(delta) {
	step = g_font.height * 5;
	offset += (delta * step);
	if(offset > 0 || textheight < wh) {
		offset = 0;
	} else {
		temp = -textheight + wh;
		if(offset < temp) offset = Math.round(temp / step) * step;
	}
	window.Repaint();
}

function on_mouse_move(x,y) {
	window.SetCursor(x > ww-60 && x < ww-10 && y > 8 && y < 26 ? IDC_HAND : IDC_ARROW);
}

function on_mouse_lbtn_up(x, y) {
	if(x > ww-60 && x < ww-10 && y > 8 && y < 26) {
		lfm_artist = artist.replace(/\s+/g,"+")
		_menu = window.CreatePopupMenu();
		_menu.AppendMenuItem(MF_STRING,1 , "Visit artist page");
		_menu.AppendMenuItem(MF_STRING,2 , "Similar artists radio");
		idx = _menu.TrackPopupMenu(ww-60, 26);
		if(idx == 1) WshShell.run("http://www.last.fm/music/" + lfm_artist);
		if(idx == 2) try { WshShell.run("lastfm://artist/" + lfm_artist + "/similarartists"); } catch(e) {fb.ShowPopupMessage("Unable to launch last.fm radio! Make sure foo_lastfm_radio is installed and that you have set your username and password in the preferences. Also, check foobar is set as the default handler for the lastfm:// protocol. Use the \"Set program association\" tool found under File>Preferences>Shell Integration.", "Error:"); }
		_menu.Dispose();
	}
}